package com.congee02.sw.var;

import java.util.HashMap;
import java.util.Map;

public class MaxSubarrayLength {

    public int maxSubarrayLength(int[] nums, int k) {

        int n = nums.length;

        Map<Integer, Integer> cnt = new HashMap<>();

        // l = r = 0
        add(cnt, nums[0]);
        int ans = 1;

        int l = 0;
        for (int r = 1 ; r < n ; r ++ ) {
            while (get(cnt, nums[r]) >= k) {
                decrease(cnt, nums[l ++]);
            }
            add(cnt, nums[r]);
            ans = Math.max(ans, r - l + 1);
        }

        return ans;
    }

    private void add(Map<Integer, Integer> cnt, int x) {
        cnt.put(x, cnt.getOrDefault(x, 0) + 1);
    }

    private void decrease(Map<Integer, Integer> cnt, int x) {
        cnt.put(x, cnt.get(x) - 1);
    }

    private int get(Map<Integer, Integer> cnt, int x) {
        return cnt.getOrDefault(x, 0);
    }

}
